﻿using CommunityToolkit.Mvvm.Input;
using Modbus.Device;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace Modbus数据开关量读取控制
{
    internal class MainViewModel
    {
        public ObservableCollection<string> COMList { get; set; }
        public RelayCommand<string> StartCommand { get; set; }
        public RelayCommand<string> COMCommand { get; set; }
        ModbusMaster modbus;
        public MainViewModel()
        {
            COMList = new ObservableCollection<string>();
            SerialPort.GetPortNames().ToList().ForEach(x => COMList.Add(x));
            SerialPort serialPort = new SerialPort();
            StartCommand = new RelayCommand<string>((x) =>
            {
                if (string.IsNullOrEmpty(x))
                {
                    MessageBox.Show("请选择串口");
                    return;
                }
                try
                {
                    serialPort = new SerialPort()
                    {
                        BaudRate = 9600,
                        PortName = x,
                        Parity = Parity.None,
                        StopBits = StopBits.One,
                        DataBits = 8
                    };
                    serialPort.Open();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    return;
                }

                modbus = ModbusSerialMaster.CreateRtu(serialPort);
                MessageBox.Show("连接成功");
            });

            COMCommand = new RelayCommand<string>(x =>
            {
                if (modbus is null)
                {
                    MessageBox.Show("请连接串口");
                    return;
                }
                ushort i = ushort.Parse(x);
                bool b = !modbus.ReadCoils(1, (ushort)(i - 1), 1)[0];
                modbus.WriteSingleCoil(1, (ushort)(i - 1), b);
            });
        }
    }
}
